<?php


namespace app\common\service\finance\merchant;


use app\agent\model\Withdraw as WithdrawModel;
use app\model\Agent;
use app\model\AgentMerchantStat;
use app\model\AgentMerchantStatItem;
use app\model\AgentMerchantWithdraw;
use app\model\AgentMerchantWithdrawItem;
use app\model\AgentWithdraw;
use Carbon\Carbon;
use think\Exception;
use think\facade\Db;
use think\Log;

/**
 * 有美惠充发起提现
 * Class MerchantService
 * @package app\common\service\finance\merchant
 */
class WithdrawService
{

    public $log = [];

    public $total_amount = 0;

    public $merchant_id;

    public $agentMerchantStatIds = [];

    public $agentWithdrawIds =[];


    /**
     * 提交提现
     */
    public function submit($params)
    {



        $ids = $params['ids'] ?? [];
        $merchant_id = $params['merchant_id'] ?? 0;
        $this->merchant_id = $merchant_id;

        Db::startTrans();

        try {

            //事务
            $amountAgent = $this->handleBaseData($merchant_id, $ids);  //处理状态

            if (empty($amountAgent)) {
                throw new Exception('暂无可提现数据');
            }
            $this->log[] = $amountAgent;

            foreach ($amountAgent as $agent_id => $amount) {

                //提现银行卡信息处理 ---走以前的逻辑
                $params['amount'] = $amount;
                $this->total_amount += $amount;
                $agentWithdraw = AgentWithdraw::create([  //事件去扣金额
                    'agent_id' => $agent_id,
                    'amount' => $amount,
                    'charge' => 0, //手续费
                    'real_price' => $amount, //真实金额 扣除了手续费
                    'type' => $params['type'] ?? 0,
                    'alipay' => $params['alipay'] ?? '',
                    'mobile' => $params['mobile'] ?? '',
                    'wechat' => $params['wechat'] ?? '',
                    'bank_card_no' => $params['bank_card_no'] ?? '',
                    'bank_username' => $params['bank_username'] ?? '',
                    'bank_name' => $params['bank_name'] ?? '',
                    'user_remark' => $params['user_remark'] ?? '',
                    'status' => AgentWithdraw::STATUS_WAIT,//待审核
                    'from' =>AgentWithdraw::FROM_YMSH,
                ]);
                $this->agentWithdrawIds[] = $agentWithdraw->id;
            }




            if (!$this->total_amount){
                $this->log[] = '查询到没有数据';
                return  false;
            }

             $record =  $this->saveRecord();

            if ($record){
                Db::commit();
            }else{
                Db::rollback();
            }

            return  $record;

        } catch (Exception $exception) {

            Db::rollback();
            \think\facade\Log::error($exception->getMessage());
            throw new Exception($exception->getMessage());
        }

        return true;

    }


    /**
     * 获取数据，同时更新状态
     * @param $merchant_id
     * @param $ids
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handleBaseData($merchant_id, $ids)
    {


        $amountAgent = [];

        AgentMerchantStat::query()
            ->where('merchant_id', $merchant_id)
            ->whereIn('id', $ids)
            ->select()->each(function ($agentMerchantStat) use (&$amountAgent) {
                /**
                 * @var AgentMerchantStat $agentMerchantStat
                 */
                if ($agentMerchantStat->status != AgentMerchantStat::STATUS_WAIT) {
                    throw new Exception('提现的状态错误，已提交状态id：' . $agentMerchantStat->id);
                };

                //代理商金额汇总
                $agentMerchantStatItems = $agentMerchantStat->agentMerchantStatItem;

                collect($agentMerchantStatItems)->each(function ($agentMerchantStatItem) use (&$amountAgent) {

                    /**
                     * @var AgentMerchantStatItem $agentMerchantStatItem
                     */
                    if (empty($amountAgent[$agentMerchantStatItem->agent_id])) $amountAgent[$agentMerchantStatItem->agent_id] = 0;

                    $amountAgent[$agentMerchantStatItem->agent_id] += $agentMerchantStatItem->amount;

                });

                $this->log[] = '修改AgentMerchantStat 状态为待核验id为：' . $agentMerchantStat->id;

                $agentMerchantStat->status = AgentMerchantStat::STATUS_ACCOUNTING;
                $agentMerchantStat->submit_at = Carbon::now();
                $agentMerchantStat->save();

                $this->agentMerchantStatIds[] = $agentMerchantStat->id;

            });


        $this->log[] = '整理到提现的金额 代理商对应的金额（分）：' . PHP_EOL;
        $this->log[] = $amountAgent;

        \think\facade\Log::info($this->log);

        return $amountAgent;
    }


    /**
     * 保存记录
     */
    public function saveRecord()
    {

        $this->log[] = '去保存记录';

        //默认提现状态
        $agentMerchantWithdraw = AgentMerchantWithdraw::create([
            'merchant_id' => $this->merchant_id,
            'amount' => $this->total_amount,
        ]);

        foreach ($this->agentWithdrawIds as $agentWithdrawId) {
            AgentMerchantWithdrawItem::create([
                'agent_merchant_withdraw_id' => $agentMerchantWithdraw->id,
                'relation_id' => $agentWithdrawId,
                'type' => AgentMerchantWithdrawItem::TYPE_WITHDRAW
            ]);
        }

        foreach ($this->agentMerchantStatIds as $agentMerchantStatId) {
            AgentMerchantWithdrawItem::create([
                'agent_merchant_withdraw_id' => $agentMerchantWithdraw->id,
                'relation_id' => $agentMerchantStatId,
                'type' => AgentMerchantWithdrawItem::TYPE_STAT
            ]);
        }

        return $agentMerchantWithdraw;

    }


}